//
//  YTInvitFriendsController.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/8/3.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTInvitFriendsController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
@interface YTInvitFriendsController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property(nonatomic ,strong)WKWebView *webView;
@property(nonatomic ,strong)WKWebViewConfiguration *config;
@property(nonatomic ,strong)MBProgressHUD *loadingView;
@end

@implementation YTInvitFriendsController

- (MBProgressHUD *)loadingView
{
    if (!_loadingView) {
        _loadingView = [MBProgressHUD showHUDAddedTo:self.view animated:true];
        _loadingView.mode = MBProgressHUDModeDeterminate;
        _loadingView.label.text = @"正在加载...";
        _loadingView.bezelView.color = [UIColor colorWithHex:@"#16a5ad"];
        _loadingView.label.font = [UIFont systemFontOfSize:15];
        _loadingView.bezelView.alpha = 0.86;
        _loadingView.label.textColor = UIColor.whiteColor;

    }
    return _loadingView;
}
// lazy webview
- (WKWebView *)webView
{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:self.config];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        
        [[_webView configuration].userContentController addScriptMessageHandler:self name:@"sendImgUrl"];
        [[_webView configuration].userContentController addScriptMessageHandler:self name:@"sendClose"];
    }
    return _webView;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.loadingView.progress = self.webView.estimatedProgress;
        
        if (self.loadingView.progress == 1) {
            [self.loadingView hideAnimated:true];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc
{
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

// lazy config
- (WKWebViewConfiguration *)config
{
    if (!_config) {
        _config = [[WKWebViewConfiguration alloc] init];
        _config.userContentController = [[WKUserContentController alloc]init];
    }
    return _config;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    [self.view addSubview:self.webView];
    
    self.navigationItem.title = @"邀请好友";

    // FIXME: - 记得修改正式环境url
    // 没设置代理加载
    if (![YTNetworkManager.shareManager checkProxySetting])
    {
        NSMutableURLRequest *requestM = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@InvitingFriends/index",kMainUrlStr]]];
        [requestM setValue:YTNetworkManager.shareManager.account.auth
        forHTTPHeaderField:@"user-token"];
        
        [self.webView loadRequest:requestM];
    }else{
        [self.view showTipWithTipStr:@"网络不给力..."];
    }

    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage dh_setNavImageName:@"倛袨1"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClick)];

    self.navigationController.navigationBar.hidden = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = false;
}

// 返回按钮
- (void)backButtonClick
{
    if ([self.webView canGoBack])
    {
        [self.webView goBack];
        return;
    }
    [self.navigationController popViewControllerAnimated:true];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    // 平台首页
    if ([message.name isEqualToString:@"sendImgUrl"]) {
        //在分享按钮绑定如下触发代码
        //显示分享面板
        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
            // 根据获取的platformType确定所选平台进行下一步操作
            NSLog(@"%@",userInfo);
            [self shareWebPageToPlatformType:platformType imgUrl:message.body];//新增代码
        }];

    }
    
    // 返回
    if ([message.name isEqualToString:@"sendClose"]) {
        [self.navigationController popViewControllerAnimated:true];
    }
}

//定义实现的方法
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType imgUrl:(NSString *)imgUrl
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    //NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.model.post_title descr:self.model.post_content thumImage:self.model.purl];
//    //设置网页地址
//    shareObject.webpageUrl = self.model.shareurl;
//
//    //分享消息对象设置分享内容对象
//    messageObject.shareObject = shareObject;
    UMShareImageObject *shareOject = [[UMShareImageObject alloc] init];
    
    [shareOject setShareImage:imgUrl];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareOject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);

            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        NSLog(@"分享出错%@",error);//修改代码
    }];
}


#pragma mark: - WKNavigationDelegate



@end
